When you run a Java program, Java needs memory to:
Imagine your computer is a house:
new
keywordString name = new String("Deepak");
π Result:
One "Deepak"
in String Pool + another new object in Heap.
String s1 = "Hello"; String s2 = "Hello";
π Result: Both s1
and s2
point to the same object in
String Pool, no duplicate created.
String s1 = new String("World"); String s2 = s1.intern(); String s3 = "World";
π Result:
s2
and s3
refer to the same object in
String Pool, but s1
is a separate object in Heap.
π Important Notes on Heap & String Pool:
String
objects.intern()
intern()
is a method of String
class.String x = new String("Java"); String y = x.intern(); String z = "Java"; System.out.println(x == y); // false System.out.println(y == z); // true
π Why use intern()
?
int a = 10;
π Result: 'a' is a local variable, stored in Stack
static int collegeCode = 123;
π Result: 'collegeCode' is stored in the Method Area
public class Student { int age = 20; // Stored in Heap static String school = "ABC"; // Stored in Method Area public static void main(String[] args) { int roll = 101; // Stored in Stack Student s1 = new Student(); // Object in Heap, ref in Stack } }
Memory Area | What It Stores |
---|---|
Heap | Object s1, instance variable age |
Stack | roll, reference to s1 |
Method Area | Class info, school |
free()
like in C/C++Student s1 = new Student();
s1 = null; // Now the object is not used β eligible for GC
You can suggest GC like this:
System.gc(); // Suggests garbage collection (not guaranteed)
β Question | β Simple Answer |
---|---|
What is memory management? | Java automatically allocates and frees memory using JVM. |
What is the Heap? | Stores objects. Shared by all. Cleaned by garbage collector. |
What is Stack memory? | Stores method calls and local variables. One per thread. |
What is garbage collection? | JVM removes unused objects from memory automatically. |
Where are static variables stored? | In the Method Area. |
What is stored in Stack vs Heap? | Stack = local vars, refs. Heap = objects. |
Can you force GC in Java? | You can suggest it using System.gc(), but it's not guaranteed. |
Part | Description | Example |
---|---|---|
Heap | Stores objects | new Student() |
Stack | Stores method calls and variables | int a = 5; |
Method Area | Stores class data, static vars | static int x; |
Garbage Collection | Removes unused objects | obj = null; |